package com.qiantu.phone.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.LinearSmoothScroller;
import androidx.recyclerview.widget.RecyclerView;

import com.hjq.base.BaseAdapter;
import com.hjq.base.BaseDialog;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.hjq.toast.ToastUtils;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.bean.AddDeviceBean;
import com.qiantu.phone.bean.AddDeviceMethodBean;
import com.qiantu.phone.scan.ScanCodeActivity;
import com.qiantu.phone.ui.adapter.AddDeviceCategoryAdapter;
import com.qiantu.phone.ui.adapter.AddDeviceMethodAdapter;
import com.qiantu.phone.ui.adapter.AddDeviceTypeAdapter;
import com.qiantu.phone.ui.dialog.BottomConfigNetworkDialog;
import com.qiantu.phone.ui.dialog.BottomEditDialog;
import com.qiantu.phone.ui.dialog.ConfirmHintDialog;
import com.qiantu.phone.utils.AddDeviceParseUtil;
import com.qiantu.phone.utils.TopSmoothScroller;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.interfaces.SimpleCallback;

import java.util.List;

/**
 * author : Android 轮子哥
 * github : https://github.com/getActivity/AndroidProject
 * time   : 2018/10/18
 */
public final class AddDevice1Activity extends AppActivity {

    public static final int TYPE_WIRED_ADD = 1;
    public static final int TYPE_WIFI_ADD = 2;
    public static final int TYPE_CODE_ADD = 3;

    private RecyclerView leftRecyclerView;
    private RecyclerView rightRecyclerView;
    private AddDeviceTypeAdapter mAddDeviceTypeAdapter;
    private AddDeviceCategoryAdapter mAddDeviceCategoryAdapter;
    private BottomConfigNetworkDialog mBottomConfigNetworkDialog;
    private AddDeviceBean.DeviceConfigNetworkBean mDeviceConfigNetworkBean;
    private AddDeviceMethodAdapter mAddDeviceMethodAdapter;
    private AddDeviceMethodBean mAddDeviceMethodBean;
    //序列号
    private String deviceSn;
    private XXPermissions xxPermissions;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_add_device1;
    }

    @Override
    protected void initView() {
        leftRecyclerView = findViewById(R.id.left_recycler_view);
        rightRecyclerView = findViewById(R.id.right_recycler_view);
        setOnClickListener(R.id.btn_scan_add);
        initListView();
    }

    private void initListView() {
        mAddDeviceTypeAdapter = new AddDeviceTypeAdapter(this);
        LinearLayoutManager leftLinearLayoutManager = new LinearLayoutManager(this);
        leftRecyclerView.setLayoutManager(leftLinearLayoutManager);
        leftRecyclerView.setAdapter(mAddDeviceTypeAdapter);
        mAddDeviceCategoryAdapter = new AddDeviceCategoryAdapter(this);
        LinearLayoutManager rightLinearLayoutManager = new LinearLayoutManager(this);
        rightRecyclerView.setLayoutManager(rightLinearLayoutManager);
        rightRecyclerView.setAdapter(mAddDeviceCategoryAdapter);
        mAddDeviceTypeAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                LinearSmoothScroller lss = new TopSmoothScroller(getApplicationContext());
                lss.setTargetPosition(position);
                rightLinearLayoutManager.startSmoothScroll(lss);
                mAddDeviceTypeAdapter.selectItem(position);
            }
        });
        rightRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int firstVisibleItemPosition = rightLinearLayoutManager.findFirstVisibleItemPosition();
                leftLinearLayoutManager.scrollToPositionWithOffset(firstVisibleItemPosition - 5 < 0 ? 0 : firstVisibleItemPosition - 5, 0);
                mAddDeviceTypeAdapter.selectItem(firstVisibleItemPosition);
            }
        });
        mAddDeviceCategoryAdapter.setOnItemClickListener(new AddDeviceCategoryAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(AddDeviceBean.DeviceConfigNetworkBean deviceConfigNetworkBean) {
                mDeviceConfigNetworkBean = deviceConfigNetworkBean;
                showBottomConfigNetworkDialog();
            }
        });
    }

    @Override
    protected void initData() {
        List<AddDeviceBean> data = AddDeviceParseUtil.parseData(getContext());
        mAddDeviceTypeAdapter.setData(data);
        mAddDeviceCategoryAdapter.setData(data);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_scan_add:
                if(xxPermissions == null){
                    xxPermissions = XXPermissions.with(getActivity());
                }
                String[] permissions = new String[]{
                        Manifest.permission.CAMERA
                };
                if(!XXPermissions.isGranted(getContext(),permissions) && AppApplication.isHuawei() ){
                    showConfirmHintDialog("App需要使用您的相机权限，来扫描TLC1上的二维码，以进行后续的设备添加功能。如若已拒绝，再使用本功能前请先前往手机设置中将本应用的相机权限改为允许。");
                }else{
                    requestPermission();
                }
                break;
//            case R.id.btn_bluetooth_add:
//                Intent intent = new Intent(this, BluetoothAddDeviceActivity.class);
//                startActivity(intent);
//                break;
        }
    }

    private void showBottomConfigNetworkDialog() {
        if (mBottomConfigNetworkDialog == null) {
            mBottomConfigNetworkDialog = new BottomConfigNetworkDialog(this);
            new XPopup.Builder(this)
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomConfigNetworkDialog);
            mAddDeviceMethodAdapter = new AddDeviceMethodAdapter(getContext());
            mBottomConfigNetworkDialog.setAdapter(mAddDeviceMethodAdapter);
        }
        mAddDeviceMethodAdapter.setData(mDeviceConfigNetworkBean.getLinks());
        mAddDeviceMethodAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                mAddDeviceMethodBean = mAddDeviceMethodAdapter.getItem(position);
                switch (mAddDeviceMethodBean.getProductLinkType()){
                    case TYPE_WIRED_ADD:
                        showBottomEditDialog();
                        break;
                    case TYPE_WIFI_ADD:
                        mBottomConfigNetworkDialog.dismiss();
                        next();
                        break;
                }
            }
        });
        mBottomConfigNetworkDialog.show();
    }

    private BottomEditDialog mBottomEditDialog;
    private void showBottomEditDialog() {
        if (mBottomEditDialog == null) {
            mBottomEditDialog = new BottomEditDialog(this);
            mBottomEditDialog.setOnConfirmDismiss(false);
            mBottomEditDialog.setDialogClickListener(new BottomEditDialog.DialogClickListener() {
                @Override
                public void onConfirmClick() {
                    deviceSn = mBottomEditDialog.getText();
                    if(TextUtils.isEmpty(deviceSn)){
                        toast(R.string.please_enter_serial_number);
                        return;
                    }
                    mBottomEditDialog.dismiss();
                    next();
                }
            });
            new XPopup.Builder(this)
                    .setPopupCallback(new SimpleCallback(){
                        @Override
                        public void onShow(BasePopupView popupView) {
                            postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    mBottomConfigNetworkDialog.dismiss();
                                }
                            }, 500);
                        }
                    })
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomEditDialog);
        }
        mBottomEditDialog.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
        mBottomEditDialog.setLabel(getString(R.string.serial_number_add));
        mBottomEditDialog.setBtnText(getString(R.string.add));
        mBottomEditDialog.setHint(getString(R.string.please_enter_serial_number));
        mBottomEditDialog.show();
    }

    private BaseDialog mConfirmHintDialog;
    private ConfirmHintDialog.Builder mConfirmHintDialogBuilder;

    private void showConfirmHintDialog(String text) {
        if (mConfirmHintDialog == null) {
            mConfirmHintDialogBuilder = new ConfirmHintDialog.Builder(getActivity())
                    .setRightBtnText(getString(R.string.ok))
                    .setListener(new ConfirmHintDialog.OnListener() {
                        @Override
                        public void onLeftClick(BaseDialog dialog) {
                            finish();
                        }

                        @Override
                        public void onConfirm(BaseDialog dialog) {
                            requestPermission();
                        }
                    });
            mConfirmHintDialog = mConfirmHintDialogBuilder.create();
        }
        mConfirmHintDialogBuilder.setCancelable(false);
//        mConfirmHintDialogBuilder.setCanceledOnTouchOutside(false);
        mConfirmHintDialogBuilder.setContent(text);
        mConfirmHintDialog.show();
    }

    private void requestPermission(){
        xxPermissions.permission(Manifest.permission.CAMERA)
                .request(new OnPermissionCallback() {
                    @Override
                    public void onGranted(List<String> permissions, boolean all) {
                        if(all){
                            Intent intent = new Intent(getContext(), ScanCodeActivity.class);
                            startActivity(intent);
                        }
                    }
                    @Override
                    public void onDenied(List<String> permissions, boolean never) {
                        ToastUtils.show(R.string.common_permission_fail_1);
                    }

                });
    }

    private void next(){
        Intent intent = new Intent(getContext(), AddDevice2Activity.class);
        intent.putExtra("addDeviceName", mDeviceConfigNetworkBean.getProductInfo().getName());
        intent.putExtra("productLinkType", mAddDeviceMethodBean.getProductLinkType());
        intent.putExtra("deviceSn", deviceSn);
        intent.putExtra("productModel", mDeviceConfigNetworkBean.getProductInfo().getProductModel());
        intent.putParcelableArrayListExtra("links", mDeviceConfigNetworkBean.getLinks());
        startActivity(intent);
    }
}